import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        cartList: uni.getStorageSync("cartList") || [],
        token: ""
    },
    // getter 相当与 vuex中的计算属性！！ 
    // 对购物车当中数据 进行筛选和计算 统计 购买总数 购买 总量 
    getters: {
        // 获取勾选了的商品数组
        checkedGoods: (state) => {
            return state.cartList.filter(v => v.checked);
        },
        // 勾选的商品数量
        checkedCount: (state, getters) => {
            return getters.checkedGoods.reduce((count, goods) => count += goods.count, 0);
        },
        // 勾选了商品的价格
        countAll(state, getters) {
            // 获取全部勾选了的商品
            const checkedList = getters.checkedGoods;
            // reduce
            return checkedList.reduce(
                (sum, goods) => (sum += goods.count * goods.goods_price),
                0
            );
        },
    },

    mutations: {
        changeList(state, newList) {
            state.cartList = newList;
            console.log(state.cartList);
            // 存一份到本地存储 
            uni.setStorageSync("cartList", state.cartList);
        },
        setToken(state, token) {
            state.token = token;
        }
    }
});

export default store;